<template>
  <div class="mainDiv">
    <el-row class="contentDiv">
      <el-row
        type="flex"
        justify="space-between"
        align="middle"
        class="mb-10"
      >
        <el-col
          :span="7"
          class="flexCenter"
        >
          <label style="width: 100px">分部分项：</label
          ><el-cascader
            style="flex: 1"
            v-model="branchIdArr"
            :options="branchItemOptions"
            :props="{
              checkStrictly: true,
              expandTrigger: 'click',
              value: 'id',
              label: 'name',
              children: 'itemList',
            }"
            clearable
            @focus="getBranchItemListApi"
          ></el-cascader
        ></el-col>

        <el-col
          :span="7"
          class="flexCenter"
        >
          <label style="width: 100px">领用人：</label>
          <el-select
            style="flex: 1"
            placeholder="请选择领用人"
            v-model="recipient"
            @focus="getEnableUserListApi"
          >
            <el-option
              v-for="el in manOptions"
              :key="el.id"
              :label="el.name"
              :value="el.id"
            >
            </el-option>
          </el-select> </el-col
        ><el-col
          :span="7"
          class="flexCenter"
        >
          <label style="width: 100px">出库日期：</label>
          <el-date-picker
            style="flex: 1"
            v-model="outDate"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-col>
      </el-row>
      <el-row
        type="flex"
        justify="space-between"
        align="middle"
        class="mb-10"
      >
        <el-col
          :span="7"
          class="flexCenter"
        >
          <label style="width: 100px">里程号：</label>
          <el-row
            style="flex: 1"
            type="flex"
            justify="space-between"
            align="middle"
          >
            DK&nbsp;
            <el-input-number
              style="width: 100%"
              v-model="mileageStartKm"
              :max="1000"
              label="0"
              :controls="false"
            ></el-input-number>
            &nbsp;+&nbsp;
            <el-input-number
              style="width: 100%"
              v-model="mileageStartM"
              :max="1000"
              label="0"
              :controls="false"
            ></el-input-number
            >&nbsp;至&nbsp;&nbsp;&nbsp;&nbsp;DK&nbsp;
            <el-input-number
              style="width: 100%"
              v-model="mileageEndKm"
              :max="1000"
              label="0"
              :controls="false"
            ></el-input-number
            >&nbsp;+&nbsp;
            <el-input-number
              style="width: 100%"
              v-model="mileageEndM"
              :max="1000"
              label="0"
              :controls="false"
            ></el-input-number>
          </el-row>
        </el-col>
        <el-col
          :span="7"
          class="flexCenter"
        >
          <label style="width: 100px">物料名称：</label
          ><el-cascader
            style="flex: 1"
            v-model="materialArr"
            :show-all-levels="false"
            :options="materialOptions"
            :props="{
              expandTrigger: 'click',
              value: 'id',
              label: 'name',
              children: 'children',
            }"
            placeholder="请选择物料名称"
            @focus="getMaterialTreeApi"
          ></el-cascader>
        </el-col>
        <el-col
          :span="7"
          class="flexCenter"
          ><label style="width: 100px">规格型号：</label
          ><el-select
            style="flex: 1"
            v-model="modelId"
            placeholder="规格型号"
            @focus="selectModelHandler"
          >
            <el-option
              v-for="(item, index) in typeSearchOptions"
              :key="index + 't'"
              :label="item.model"
              :value="item.id"
            >
            </el-option> </el-select
        ></el-col>
      </el-row>
      <el-row
        type="flex"
        justify="space-between"
        align="middle"
      >
        <el-col :span="16">
          <el-button
            type="warning"
            @click="exportHandler"
            >批量导出</el-button
          >
          <el-button
            type="primary"
            @click="shuaxin"
            >刷新</el-button
          >
        </el-col>
        <el-col
          :span="8"
          class="text-r"
          ><el-button
            type="primary"
            @click="searchHandler"
            >查询</el-button
          ><el-button
            plain
            @click="resetHandler"
            >重置</el-button
          ></el-col
        >
      </el-row>
    </el-row>
    <el-row class="contentDiv mb-10">
      <div id="printTable">
        <div style="font-size: 8px; text-align: right; margin-top: -20px">
          创建时间：{{ printCreateTime }}
        </div>
        <table
          cellspacing="0"
          border="1"
          align="center"
          frame="void"
          rules="all"
          style="display: block; width: 100%; font-size: 12px; margin-top: 5px"
        >
          <tbody>
            <tr
              v-for="(item, index) in cData"
              :key="index"
              style="height: 30px"
              :class="index === 0 ? 'rowOneBgc' : ''"
            >
              <td
                v-if="index === cData.length - 3"
                rowspan="3"
                style="width: 120px; text-align: center"
              >
                {{ item.title }}
              </td>
              <template v-else-if="index > cData.length - 3"></template>
              <td
                v-else
                style="width: 120px; text-align: center"
              >
                {{ item.title }}
              </td>
              <td style="width: 220px; text-align: center">
                {{ item.content }}
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <el-table
        :data="renderData"
        border
        style="width: 100%"
        height="685"
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
        @select="handleSelecChange"
        @selection-change="handleSelectionChange"
        ref="multipleTable"
        :row-key="(row) => row.id"
      >
        <el-table-column
          type="selection"
          width="55"
          reserve-selection
        >
        </el-table-column>
        <el-table-column
          fixed
          type="index"
          label="序号"
          width="55"
        >
        </el-table-column>
        <el-table-column
          prop="supplierName"
          label="供应商"
          min-width="150"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="batchNum"
          label="批号"
          min-width="150"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="batchNum"
          label="里程号"
          min-width="200"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            DK{{
              scope.row.mileageStartKm != null
                ? scope.row.mileageStartKm < 10
                  ? `00${scope.row.mileageStartKm}`
                  : scope.row.mileageStartKm < 100
                  ? `0${scope.row.mileageStartKm}`
                  : scope.row.mileageStartKm
                : '-'
            }}+{{
              scope.row.mileageStartM != null
                ? scope.row.mileageStartM < 10
                  ? `00${scope.row.mileageStartM}`
                  : scope.row.mileageStartM < 100
                  ? `0${scope.row.mileageStartM}`
                  : scope.row.mileageStartM
                : '-'
            }}~DK{{
              scope.row.mileageEndKm != null
                ? scope.row.mileageEndKm < 10
                  ? `00${scope.row.mileageEndKm}`
                  : scope.row.mileageEndKm < 100
                  ? `0${scope.row.mileageEndKm}`
                  : scope.row.mileageEndKm
                : '-'
            }}+{{
              scope.row.mileageEndKm != null
                ? scope.row.mileageEndM < 10
                  ? `00${scope.row.mileageEndM}`
                  : scope.row.mileageEndM < 100
                  ? `0${scope.row.mileageEndM}`
                  : scope.row.mileageEndM
                : '-'
            }}</template
          >
        </el-table-column>

        <el-table-column
          prop="branchName"
          label="分部工程"
          min-width="150"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="branchItemName"
          label="分项工程"
          min-width="150"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="materialName"
          label="物料名称"
          min-width="150"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="modelName"
          label="规格型号"
          min-width="150"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="recipientName"
          label="领用人"
          min-width="150"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="modelName"
          label="生成文件"
          min-width="250"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <div>
              <el-button
                type="primary"
                style="background-color: #409eff"
                @click="downloadFileHandler(scope.row)"
                >下载审批单</el-button
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="outDate"
          label="出库日期"
          min-width="150"
          show-overflow-tooltip
        >
        </el-table-column>
        <template #empty>
          <el-empty v-loading="loading"></el-empty>
        </template>
      </el-table>
    </el-row>
    <el-row class="contentDiv text-r"
      ><el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[10, 20, 50]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination
    ></el-row>
  </div>
</template>

<script>
import {
  getTracePage,
  getTraceExport,
} from '/src/http/materialDispatch/materTrack.js'
import {
  getBranchItemList,
  getEnableUserList,
  getMaterialTypeDetail,
  getMaterialDetail,
  getMaterialTree,
  downloadFile,
  getProcessLog,
} from '/src/http/commonApi.js'

import download from '/src/utils/downLoad.js'
import printJS from 'print-js'
export default {
  data() {
    return {
      loading: false,
      cData: [],
      isSearch: false,
      renderData: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      branchItemOptions: [],
      manOptions: [],
      materialOptions: [],
      branchIdArr: [],
      typeSearchOptions: [],
      modelId: null,
      recipient: null,
      materialArr: [],
      mileageStartKm: undefined,
      mileageStartM: undefined,
      mileageEndKm: undefined,
      mileageEndM: undefined,
      outDate: [],

      multipleSelection: [],
      multipleSelectionIds: [],

      printCreateTime: '',
    }
  },

  mounted() {
    this.getTracePageApi()
  },

  methods: {
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0 && rowIndex == this.cData.length - 3) {
        return [3, 1]
      }
      if (columnIndex === 0 && rowIndex >= this.cData.length - 3) {
        return [0, 0]
      }
      return [1, 1]
    },

    downloadFileHandler(item) {
      console.log('item::: ', item)
      this.printCreateTime = item.createTime
      let contentArr = [
        item.woNum,
        item.createByName,
        item.supplierName,
        item.batchNum,
        item.branchName,
        item.branchItemName,
        `DK${item.mileageStartKm}+${item.mileageStartM}~DK${item.mileageEndKm}+${item.mileageEndM}`,
        item.materialName,
        item.modelName,
        item.outNum,
        item.outAmount,
        item.recipientName,
        item.outDate,
      ]
      let proccessLogData = []
      let titleArr = [
        '出库单号',
        '制单人',
        '供应商',
        '批号',
        '分部工程',
        '分项工程',
        '施工里程',
        '物料名称',
        '规格型号',
        '出库数量',
        '出库金额',
        '领用人',
        '出库日期',
        '审批流程',
        '审批流程',
        '审批流程',
      ]
      getProcessLog({ id: item.orderId }).then((res) => {
        if (res.code == 200) {
          if (res.data.logVoList && res.data.logVoList.length > 0) {
            res.data.logVoList.shift()
            res.data.logVoList.pop()
            for (let i = 0; i < res.data.logVoList.length; i++) {
              proccessLogData.push({
                operatorName: res.data.logVoList[i].operatorName,
                opinion: res.data.logVoList[i].opinion,
                finishTime: res.data.logVoList[i].finishTime,
              })
            }

            contentArr = contentArr.concat(proccessLogData)
          }
          for (let i = 0; i < titleArr.length; i++) {
            if (i > contentArr.length - 4) {
              this.cData.push({
                title: titleArr[i],
                content:
                  contentArr[i].operatorName +
                  ' ' +
                  ' ' +
                  contentArr[i].opinion +
                  ' ' +
                  ' ' +
                  contentArr[i].finishTime,
              })
            } else {
              this.cData.push({
                title: titleArr[i],
                content: contentArr[i],
              })
            }
          }

          this.$nextTick(() => {
            let printTable = document.getElementById('printTable')
            printTable.style.display = 'block'

            const style =
              '@page { size:  21cm 29.7cm; margin: 0 auto;padding: 5px 20px 20px 20px;}' +
              '@media print {body {zoom:2} .rowOneBgc{-webkit-print-color-adjust: exact;background-color: rgb(232, 232, 232);}}'
            printJS({
              printable: 'printTable',
              type: 'html',
              scanStyles: false,
              targetStyles: ['*'],

              style: style,
              scanStyles: false,
              header: `<h5 style='text-align:center'>出库审批单</h5>`,
              footer: '',
            })
            printTable.style.display = 'none'
            this.cData = []
          })
        }
      })
    },

    searchHandler() {
      this.isSearch = true
      this.pageNum = 1
      this.getTracePageApi(
        this.pageNum,
        this.pageSize,
        this.branchIdArr[0],
        this.branchIdArr[1],
        this.recipient,
        this.materialArr[this.materialArr.length - 1],
        this.modelId,
        this.mileageStartKm,
        this.mileageStartM,
        this.mileageEndKm,
        this.mileageEndM,
        this.outDate
      )
    },

    resetHandler() {
      this.multipleSelection = []
      this.$refs.multipleTable.clearSelection()
      this.isSearch = false
      this.branchIdArr = []
      this.recipient = null
      this.materialArr = []
      this.typeSearchOptions = []
      this.modelId = null
      this.mileageStartKm = undefined
      this.mileageStartM = undefined
      this.mileageEndKm = undefined
      this.mileageEndM = undefined
      this.outDate = []
      this.pageNum = 1
      this.pageSize = 10
      this.getTracePageApi()
    },

    shuaxin() {
      this.$router.go(0)
    },

    handleSelecChange(selecteds, row) {
      if (!this.multipleSelectionIds.includes(row.id)) {
        this.multipleSelectionIds.push(row.id)
        this.multipleSelection.push(row)
      } else {
        this.multipleSelection.forEach((id, index) => {
          if (id === row.id) {
            this.multipleSelectionIds.splice(index, 1)
            this.multipleSelection.splice(index, 1)
          }
        })
      }
    },
    selectModelHandler() {
      if (this.materialArr || this.materialArr.length == 0) {
        this.$message.info('请先选择物料名称')
      } else {
        getMaterialDetail(this.materialArr[this.materialArr.length - 1]).then(
          (res) => {
            this.typeSearchOptions = []
            if (res.code == 200) {
              this.typeSearchOptions = res.data
              this.modelId = null
            }
          }
        )
      }
    },

    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    exportHandler() {
      if (this.multipleSelection.length == 0) {
        if (this.isSearch) {
          let params = {
            ids: '',
            branchId: this.branchIdArr[0],
            branchItemId: this.branchIdArr[1],
            recipient: this.recipient,
            materialId: this.materialArr[this.materialArr.length - 1],
            modelId: this.modelId,
            mileageStartKm: this.mileageStartKm,
            mileageStartM: this.mileageStartM,
            mileageEndKm: this.mileageEndKm,
            mileageEndM: this.mileageEndM,
          }
          if (this.outDate.length > 0) {
            if (this.outDate[0] == this.outDate[1]) {
              params.outDate = this.outDate[0]
            } else {
              params.outStartDate = this.outDate[0]
              params.outEndDate = this.outDate[1]
            }
          }
          this.getTraceExportApi(params)
        } else {
          this.getTraceExportApi()
        }
      } else {
        let ids = this.multipleSelection.map((el) => {
          return el.id
        })
        let params = { ids: ids.join(',') }
        this.getTraceExportApi(params)
      }
    },

    handleSizeChange(val) {
      this.pageNum = 1
      this.pageSize = val
      if (this.isSearch) {
        this.getTracePageApi(
          this.pageNum,
          this.pageSize,
          this.branchIdArr[0],
          this.branchIdArr[1],
          this.recipient,
          this.materialArr[this.materialArr.length - 1],
          this.modelId,
          this.mileageStartKm,
          this.mileageStartM,
          this.mileageEndKm,
          this.mileageEndM,
          this.outDate
        )
      } else {
        this.getTracePageApi(this.pageNum, this.pageSize)
      }
    },

    handleCurrentChange(val) {
      this.pageNum = val
      if (this.isSearch) {
        this.getTracePageApi(
          this.pageNum,
          this.pageSize,
          this.branchIdArr[0],
          this.branchIdArr[1],
          this.recipient,
          this.materialArr[this.materialArr.length - 1],
          this.modelId,
          this.mileageStartKm,
          this.mileageStartM,
          this.mileageEndKm,
          this.mileageEndM,
          this.outDate
        )
      } else {
        this.getTracePageApi(this.pageNum, this.pageSize)
      }

      this.$nextTick(() => {
        this.renderData.forEach((item) => {
          if (this.multipleSelectionIds.includes(item.id)) {
            this.$refs.multipleTable.toggleRowSelection(item, true)
          }
        })
      })
    },

    getBranchItemListApi(pageNum = 1, pageSize = 999) {
      let params = {
        pageNum,
        pageSize,
      }
      getBranchItemList(params).then((res) => {
        if (res.code == 200) {
          this.branchItemOptions = res.data
        }
      })
    },

    getEnableUserListApi() {
      getEnableUserList().then((res) => {
        if (res.code == 200) {
          this.manOptions = res.data
        }
      })
    },

    getMaterialTreeApi() {
      getMaterialTree().then((res) => {
        if (res.code == 200) {
          this.materialOptions = res.data
        }
      })
    },

    getTracePageApi(
      pageNum = 1,
      pageSize = 10,
      branchId = null,
      branchItemId = null,
      recipient = null,
      materialId = null,
      modelId = null,
      mileageStartKm = null,
      mileageStartM = null,
      mileageEndKm = null,
      mileageEndM = null,
      outDate = []
    ) {
      let params = {
        pageNum,
        pageSize,
        branchId,
        branchItemId,
        recipient,
        materialId,
        modelId,
        mileageStartKm,
        mileageStartM,
        mileageEndKm,
        mileageEndM,
      }
      if (outDate.length > 0) {
        if (outDate[0] == outDate[1]) {
          params.outDate = outDate[0]
        } else {
          params.outStartDate = outDate[0]
          params.outEndDate = outDate[1]
        }
      }
      this.loading = true
      setTimeout(() => {
        getTracePage(params).then((res) => {
          if (res.code == 200) {
            this.renderData = res.data.records
            this.total = res.data.total
            this.loading = false
          }
        })
      }, 300)
    },

    getTraceExportApi(params) {
      let loading = this.$loading({
        lock: true,
        text: '导出中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      getTraceExport(params)
        .then((res) => {
          download.excel(res, `物资追踪${Date.now()}.xlsx`)

          this.$refs.multipleTable.clearSelection()
          this.multipleSelection = []
          loading.close()
        })
        .catch((err) => {
          this.$message.error('导出失败')
          loading.close()
        })
    },
  },
}
</script>

<style lang="less" scoped>
table {
  border-top: 1px solid #000000;
  border-left: 1px solid #000000;
  border-collapse: collapse;
}
td {
  border-bottom: 1px solid #000000;
  border-right: 1px solid #000000;
}
.rowOneBgc {
  -webkit-print-color-adjust: exact;
  background-color: rgb(232, 232, 232);
}
</style>
